package com.cr.admin.business.driverlicense.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cr.admin.business.audit.pojo.dto.AuditSaveParam;
import com.cr.admin.business.audit.service.AuditService;
import com.cr.admin.business.authentication.pojo.dto.query.AuthenticationQuery;
import com.cr.admin.business.authentication.pojo.vo.AuthenticationVO;
import com.cr.admin.business.authentication.service.AuthenticationService;
import com.cr.admin.business.driverlicense.mapper.DriverLicenseMapper;
import com.cr.admin.business.driverlicense.pojo.dto.param.DriverLicenseSaveParam;
import com.cr.admin.business.driverlicense.pojo.dto.param.DriverLicenseUpdateParam;
import com.cr.admin.business.driverlicense.pojo.dto.query.DriverLicenseQuery;
import com.cr.admin.business.driverlicense.pojo.entity.DriverLicense;
import com.cr.admin.business.driverlicense.pojo.vo.DriverLicenseVO;
import com.cr.admin.business.driverlicense.service.DriverLicenseService;
import com.cr.common.exception.ServiceException;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class DriverLicenseServiceImpl implements DriverLicenseService {
    @Autowired
    private DriverLicenseMapper driverLicenseMapper;
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private AuditService auditService;
    @Override
    public DriverLicenseVO getDriverLicenseDetail(Long id) {

        DriverLicenseVO driverLicenseVO = new DriverLicenseVO();

        QueryWrapper<DriverLicense> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        List<DriverLicense> list = driverLicenseMapper.selectList(queryWrapper);
        if(!list.isEmpty()){
            DriverLicense driverLicense = list.get(0);
            BeanUtils.copyProperties(driverLicense, driverLicenseVO);
            return driverLicenseVO;

        }
        return null;
    }

    @Override
    public void addDriverLicense(DriverLicenseSaveParam driverLicenseSaveParam) {
        //需先填写证件认证, 无论是否审核通过
        AuthenticationQuery authenticationQuery = new AuthenticationQuery();
        authenticationQuery.setUserId(driverLicenseSaveParam.getUserId());
        List<AuthenticationVO> list = authenticationService.list(authenticationQuery);
        if(list.isEmpty()){
            log.debug("未填写证件认证");
            throw new ServiceException("未填写证件认证");
        }else {
            long userId = driverLicenseSaveParam.getUserId();

            DriverLicense driverLicense = new DriverLicense();
            BeanUtils.copyProperties(driverLicenseSaveParam, driverLicense);
            driverLicense.setUserId(userId);

            //yyyy-mm-dd格式字符串转date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Date validStart = null;
            Date validEnd = null;
            Date birthday = null;
            try {
                validStart = sdf.parse(driverLicenseSaveParam.getValidDateStart());
                validEnd = sdf.parse(driverLicenseSaveParam.getValidDateEnd());
                birthday = sdf.parse(driverLicenseSaveParam.getBirthday());
                //设置出生日期
                driverLicense.setBirthday(birthday);

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

            Date now = new Date();
            //证件是否有效
            if(validEnd.after(now) && now.after(validStart)){
                driverLicense.setValidationStatus(0);
                driverLicense.setValidDateStart(validStart);
                driverLicense.setValidDateEnd(validEnd);
            }else{
                throw new ServiceException("证件有效日期错误");

            }
            //设置审核中
            driverLicense.setAuditing(1);
            driverLicense.setApplicationId(generateUniqueOrderNumber());

            QueryWrapper<DriverLicense> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            int result  = driverLicenseMapper.update(driverLicense, queryWrapper);
            if(result == 0 ){
                driverLicenseMapper.insert(driverLicense);
            }
            AuditSaveParam auditSaveParam = new AuditSaveParam();
            auditSaveParam.setApplicationId(driverLicense.getApplicationId());
            auditService.addDriverLicenseAudit(auditSaveParam);
        }

    }

    @Override
    public List<DriverLicenseVO> list(DriverLicenseQuery driverLicenseQuery) {
        List<DriverLicenseVO> driverLicenseVOS = new ArrayList<>();
        QueryWrapper<DriverLicense> queryWrapper = new QueryWrapper<>();
        if(driverLicenseQuery.getUserId()!=null){
            queryWrapper.eq("user_id", driverLicenseQuery.getUserId());
        }
        if(driverLicenseQuery.getAuditing()!=null){
            queryWrapper.eq("auditing", driverLicenseQuery.getAuditing());
        }
        if(driverLicenseQuery.getValidationStatus()!=null){
            queryWrapper.eq("validation_status", driverLicenseQuery.getValidationStatus());
        }
        List<DriverLicense> list = driverLicenseMapper.selectList(queryWrapper);
        for(DriverLicense driverLicense : list){
            DriverLicenseVO driverLicenseVO = new DriverLicenseVO();
            BeanUtils.copyProperties(driverLicense, driverLicenseVO);
            driverLicenseVOS.add(driverLicenseVO);
        }
        return driverLicenseVOS;
    }

    @Override
    public void updateById(DriverLicenseUpdateParam driverLicenseUpdateParam) {
        DriverLicense driverLicense = new DriverLicense();
        BeanUtils.copyProperties(driverLicenseUpdateParam, driverLicense);


        driverLicenseMapper.updateById(driverLicense);

    }

    @Override
    public void deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ServiceException("参数不能为空");
        }
        driverLicenseMapper.deleteBatchIds(ids);
        //删除审核记录 TODO

    }

    // 生成唯一的订单号
    private String generateUniqueOrderNumber() {
        // 这里可以根据业务需求生成唯一的订单号，例如使用数据库的序列、UUID、时间戳+随机数等方式生成
        Random random = new Random();
        long currentTime = System.currentTimeMillis();
        long orderNumber = currentTime * 1000 + random.nextInt(1000); // 保证足够唯一性
        return String.valueOf(orderNumber);
    }
}
